package timesheet.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import timesheet.repository.UserRepository;
import timesheet.model.Users;
@Controller
@Transactional
public class RegisterController {

	@Autowired UserRepository userRepository;
	
	@RequestMapping("/registersubmit")
	public ModelAndView registerSubmit(@RequestParam("identifier") String pseudo,
            @RequestParam(value="password",required=false) String password,@RequestParam("sex") String sex,
            @RequestParam("firstname") String firstname,@RequestParam("name") String name, 
            WebRequest request){
		ModelAndView mv = new ModelAndView("home");
		String message = "";
		Users user = new Users();
		if(!pseudo.isEmpty() && !password.isEmpty()){
		   if(userRepository.getUserByUserName(pseudo) == null){
		   user.setPassword(password);
		   user.setPseudo(pseudo);
		   user.setName(name);
		   user.setFirstname(firstname);
		   user.setRole("user");
		   user.setSex(sex);
		   userRepository.createUser(user);
		   message ="Your account has been created!";
		   mv.addObject("messageOk", message);
		   return mv;
		   }
		   else{
				message="User already registred";
				mv.addObject("messageNok", message);
				return mv;
		   }
		}
		return mv;
	}

}
